/* @(#)test.c
 * Time-stamp: <2008-10-25 16:29:18 root>
 * Copyright 2008 Julian Qian
 * Author: root@localhost.localdomain
 * Version: $Id: test.c,v 0.0 2008/10/04 17:41:30 root Exp $
 * Keywords: 
 */

#include <stdio.h>
#include <stdlib.h>

typedef long long devid_t;

#define DEVID_NUM 5

/* devid[12] -> devid_f[24] */
void cvt_devid(char *devid, char *devid_f){
	int i;
	char chr, chs;
	for(i=0;i<2;i++){
		chr = devid[i] >> 4;
		chr = chr & 0x0F;
		devid_f[2*i] = ((chr > 0x09)?(chr-0x0A+'A'):(chr+'0'));
		chr = devid[i] & 0x0F;
		devid_f[2*i+1] = ((chr > 0x09)?(chr-0x0A+'A'):(chr+'0'));
	}
}

void cvt_iddev(char *devid_f, char *devid){
	int i;
	char chr, chs;
	for(i=0; i<2; i++){
		chr = devid_f[2*i];
		chr = (chr>'9' ?  chr-'A'+0x0A: chr-'0');
		chs = (chr << 4) & 0xF0;
		
		chr = devid_f[2*i+1];
		chr = (chr>'9' ?  chr-'A'+0x0A: chr-'0');		
		chs = chs | (chr & 0x0F);
		devid[i] = chs;
	}
}


int cvt_ip(char *ip_str){
	char *pch;
	int sub, ip = 0;
	pch = strtok(ip_str, ".");
	while(pch != NULL){
		sub = atoi(pch);
		ip = ip * 256 + sub;
		pch = strtok( NULL, ".");
	}
	return ip;
}

void cvt_pi(int ip, char *ip_str){
	int a, b, c, d;
	d = ip & 0x000000FF;
	c = (ip >> 8) & 0x000000FF;
	b = (ip >> 16) & 0x000000FF;
	a = (ip >> 24) & 0x000000FF;
	snprintf(ip_str, 16, "%d.%d.%d.%d",a,b,c,d);
}

/* long long cvt_id(char *devid){ */
/* 	int i, id = 0; */
/* 	char chr, chs; */
/* 	for(i=0;i<5;i++){ /\* DEVID_NUM = 5 *\/ */
/* 		id = id << 8; */
/* 		id += devid[i]; */
/* 	} */
/* 	return id; */
/* } */

devid_t cvt_id(char *devid){
	int i;
	devid_t id = 0;
	memcpy(&id, devid, DEVID_NUM);
	id = id >> (8-DEVID_NUM);
	return id;
}

void cvt_di(devid_t id, char *devid){
	int i;
	devid_t tmp = id << 8*(8-DEVID_NUM);
	memcpy(devid, tmp, DEVID_NUM);
}

int main(int argc, char **argv)
{
	char buf[3];
	buf[0] = 0xAB;
	buf[1] = 0xFA;
	buf[2] = '\0';
    printf("%02hhx\n",buf[1]);
	char buff[10] = "FA";
	printf("%d\n",atoi(buff));
	printf("%d,%d,%d,%d\n",'0','1','a','A');
	cvt_devid(buf, buff);
	printf("%s\n", buff);
	memset(buf,0,3);
	cvt_iddev(buff, buf);

	int ip;
	char ip_str[16] = "9.123.148.96";
	printf("%x\n",ip = cvt_ip(ip_str));
	memset(ip_str, 0, 16);
	cvt_pi(ip + 100, ip_str);
	printf("%s\n", ip_str);

	printf("long int: %d\n", sizeof(long int));
	printf("int: %d\n", sizeof(int));
	printf("long long int: %d\n", sizeof(long long int));
	printf("unsigned int: %d\n", sizeof(unsigned int));

	char devid[] = "0C00280000000100f8000000";
	char devid1[] = "0C028000000001";
	printf("%d\n", strtol(devid, (char **)NULL, 16));

	char dd[5];
	dd[0] = 0x00;
	dd[1] = 0x28;
	dd[2] = 0x2b;
	dd[3] = 0xca;
	dd[4] = 0x0;
	printf("****************%ld\n", cvt_id(dd));
	printf("%d\n", (int)time(NULL));

	char a;
	a = 0xD0;
	printf("%x\n", a);
    return 0;
}
